package com.dreamlin.app.base.model

import androidx.lifecycle.*
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable

open class BaseViewModel : ViewModel() {
    private val compositeDisposable = CompositeDisposable()
    private val showDialog = DialogLiveData()
    private val error = MutableLiveData<String>()

    fun addDisposable(disposable: Disposable) = compositeDisposable.add(disposable)

    fun initDialog(owner: LifecycleOwner, observer: Observer<DialogBean>) =
        showDialog.observe(owner, observer)

    fun initError(owner: LifecycleOwner, observer: Observer<String>) =
        error.observe(owner, observer)

    fun setShow(dialogBean: DialogBean) {
        this.showDialog.setValue(dialogBean)
    }

    fun setError(error: String) {
        this.error.value = error
    }

    override fun onCleared() {
        compositeDisposable?.dispose()
        super.onCleared()
    }
}

class DialogLiveData : LiveData<DialogBean>() {
    public override fun setValue(value: DialogBean) {
        super.setValue(value)
    }
}

class DialogBean {
    var isShow = false
    var msg: String? = null

    companion object {
        private var showInstance: DialogBean? = null
        private var hideInstance: DialogBean? = null
        fun getShowInstance(): DialogBean {
            synchronized(DialogBean::class.java) {
                if (showInstance == null) {
                    showInstance = DialogBean()
                    showInstance?.isShow = true
                    showInstance?.msg = "数据加载中..."
                }
            }
            return showInstance!!
        }

        fun getHideInstance(): DialogBean {
            synchronized(DialogBean::class.java) {
                if (hideInstance == null) {
                    hideInstance = DialogBean()
                    hideInstance?.isShow = false
                    hideInstance?.msg = "数据加载中..."
                }
            }
            return hideInstance!!
        }

        fun newInstance(show: Boolean): DialogBean {
            val dialogBean = DialogBean()
            dialogBean.isShow = show
            dialogBean.msg = "数据加载中..."
            return dialogBean
        }
    }
}